package com.my.content.talent;


import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.my.content.bean.TalentBannerBean;
import com.my.content.bean.TalentBean;
import com.my.content.contants.Contants;
import com.my.content.utlis.OkHttpClientHelper;
import com.my.content.liveproject.R;
import com.my.content.utlis.PullToRefreshLableUtils;
import com.my.content.utlis.UIManager;
import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * A simple {@link Fragment} subclass.
 */
public class TalentFragment extends Fragment {

    @BindView(R.id.talent_img)
    ImageView talentImg;
    @BindView(R.id.talent_list)
    ListView talentList;
    @BindView(R.id.talent_pullToRefreshScrollView)
    PullToRefreshScrollView talentPullToRefreshScrollView;
    private TalentListAdapter adapter;

    Handler mHandler = new Handler() {

        private List<TalentBean.LivesBean> subData;
        private List<TalentBean.LivesBean> data;

        @Override
        //处理消息
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            //判断标志位
            switch (msg.arg1) {
                case 1:
                    //接收解析数据集合
                    data = (List<TalentBean.LivesBean>) msg.obj;
                    subData = new ArrayList<>();
                    for (int i = 0; i < 10; i++) {
                        subData.add(data.get(i));
                        talentList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                            @Override
                            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                                UIManager.startLive(getContext(),data.get(i).getStream_addr(),data.get(i).getCreator().getNick());
                            }
                        });
                    }
                    Log.i("TAG", "lives==================1" + data.size());
                    Log.i("TAG", "lives==================2" + subData.size());
//                    adapter.setData(subData);
                    break;
                case 2:
                    List<TalentBannerBean.DataBean> talentBannerBeanData = (List<TalentBannerBean.DataBean>) msg.obj;
                    Picasso.with(getActivity()).load(talentBannerBeanData.get(0).getImage()).placeholder(R.mipmap.default_room).into(talentImg);
                    break;
                case 3:
                    for (int i = 0; i < 10; i++) {
                        subData.add(subData.size(), data.get(subData.size() + i));
                    }
                    break;
                case 4:
                    if (data.get(0).equals(subData.get(0))) {
//                        Toast.makeText(getActivity(),"暂时没有比这更棒的才艺表演了",Toast.LENGTH_SHORT).show();
                    } else {
                        subData.add(0, data.get(0));
                    }
            }
            adapter.setData(subData);
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_talent, container, false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        adapter = new TalentListAdapter(getActivity());
        talentList.setAdapter(adapter);

        //获取需要的数据
        loadJson();
        //刷新
        refresh();
    }



    //上下拉刷新
    private void refresh() {
        //设置刷新的模式
        talentPullToRefreshScrollView.setMode(PullToRefreshBase.Mode.BOTH);
        //设置刷新的样式
        PullToRefreshLableUtils.setPullToRefreshScrollLable(talentPullToRefreshScrollView);
        //设置上下拉刷新的监听
        talentPullToRefreshScrollView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ScrollView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                //设置最近刷新时间
                PullToRefreshLableUtils.showScrollRefreshTime(refreshView, getActivity());
                //下拉刷新
                pullDownToRefresh();
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
                //设置最近刷新时间
                PullToRefreshLableUtils.showScrollRefreshTime(refreshView, getActivity());
                //上拉加载
                pullUpToRefresh();

            }
        });
    }

    //上拉加载数据
    private void pullUpToRefresh() {
        refreshResult(3);
    }

    //下拉刷新
    private void pullDownToRefresh() {
        refreshResult(4);
    }

    private void refreshResult(final int caseIndex) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                SystemClock.sleep(3000);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        //创建消息对象
                        Message message = mHandler.obtainMessage();
                        //设置标志位
                        message.arg1 = caseIndex;
                        //使用handler发送信息
                        mHandler.sendMessage(message);
                        talentPullToRefreshScrollView.onRefreshComplete();
                    }
                });
            }
        }).start();
    }

    private void loadJson() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //okhttp解析url

                    //list子条目地址
                    String stringFromURL = OkHttpClientHelper.getStringFromURL(getActivity(), Contants.Talent, null);
                    //轮播图地址
                    String bannerUrl = OkHttpClientHelper.getStringFromURL(getActivity(), Contants.BannerTalent, null);

                    //gson解析数据
                    Gson gson = new Gson();
                    TalentBean talentBean = gson.fromJson(stringFromURL, TalentBean.class);
                    TalentBannerBean talentBannerBean = gson.fromJson(bannerUrl, TalentBannerBean.class);

                    //得到解析所需的集合
                    final List<TalentBean.LivesBean> lives = talentBean.getLives();
                    final List<TalentBannerBean.DataBean> talentBannerBeanData = talentBannerBean.getData();

                    //运行在主线程
                    getActivity().runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            //创建消息对象
                            Message message = mHandler.obtainMessage();
                            Message message2 = mHandler.obtainMessage();
                            //设置标志位
                            message.arg1 = 1;
                            message2.arg1 = 2;
                            //设置包含内容
                            message.obj = lives;
                            message2.obj = talentBannerBeanData;
                            //使用handler发送信息
                            mHandler.sendMessage(message);
                            mHandler.sendMessage(message2);
                        }
                    });
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

}
